今天的工作是改寫 D17 提供的 gameLoop 範例,刪掉蠻多東西,也還有一些需要再調整的部分。一樣是先上扣,結尾會說明調整了哪些部分
import asyncio
import websockets
import random
import json
class GameBox:
def __init__(self):
# 初始化遊戲內部狀態
self.game_state = {}
self.is_end = False
self.active_player_id = random.choice([0,1])
def process_input(self, player_id, player_input):
# 處理玩家的輸入,這里可以根據玩家的輸入更新遊戲狀態
if self.is_end:
# 根據玩家輸入更新內部狀態
pass
def check_game_is_end(self):
# 結束遊戲
# 創建一個遊戲實例
my_game = GameBox()
# server notify
## 發送訊息給指定對象
async def _notify(conn, payload):
await conn.send(payload)
player_conns = [] # game
## 通知玩家開始
async def notify_player_active(player_id, payload):
await conn.send(payload)
## 通知玩家等待
## 通知遊戲狀態更新
## 通知完整遊戲狀態
# server API
## 玩家行動 API
def playerActionHandler(game_state, action):
return {'data': 'diff'} # diff of game_state
## 玩家抽牌 API
def playerDrawHandler(game_state):
return {'data': 'diff'} # diff of game_state
# WebSocket 伺服器處理函式
async def server(conn, path):
print(f'conn#{conn.id} connected')
player_input = get_player_input() # 獲取玩家輸入
my_game.process_input(player_input) # 處理輸入
async for payload in conn:
print('new payload', payload)
try:
request = json.loads(payload)
api = request.get("api")
args = request.get("args", [])
request_id = request.get("id")
if api == "/foo":
response = fooAPIhandler(args)
response["id"] = request_id
await conn.send(json.dumps(response))
else:
await conn.send(json.dumps({"id": request_id, "error": "Unknown API"}))
except Exception as e:
print(f"Error handling request: {e}")
# 啟動 WebSocket 伺服器
async def main():
start_server = await websockets.serve(server, "localhost", 8765)
print(f"WebSocket server started on ws://{server_host}:{server_port}")
await start_server.wait_closed()
if __name__ == "__main__":
asyncio.run(main())
調整的地方:
跟 websocket 整併的部分調整到一半,今天的進度就先到這裡了,謝謝大家縮看